package com.wb.component.astrict

import com.wb.component.Slf4j
import com.wb.component.Slf4j.Companion.log
import com.wb.component.event.MsgSend
import com.wb.component.filter.FunFilter
import com.wb.component.filter.FunFilterType
import com.wb.component.filter.FunFilters
import com.wb.entity.MsgGet
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
import org.aspectj.lang.reflect.MethodSignature
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import javax.annotation.Resource
import kotlin.jvm.Throws

@Aspect
@Slf4j
@Component
open class AstrictAspect {

    @Resource(name = "redisDBB")
    lateinit var redisDBB: RedisTemplate<String, Any>

    @Pointcut("@annotation(Astrict)")
    open fun astrict() {
    }

    @Throws(Exception::class)
    @Around("astrict()")
    open fun astrictBefore(point: ProceedingJoinPoint) {

        var msgGet: MsgGet? = null
        point.args.forEach {
            when (it) {
                is MsgGet -> msgGet = it
            }
        }

        if (msgGet == null) {
            log.warn("限流方法监听 => 没有读取到消息")
            return
        }

        val method = (point.signature as MethodSignature).method

        if (method.isAnnotationPresent(Astrict::class.java)) {

            val astrict = method.getAnnotation(Astrict::class.java)

            if (redisDBB.hasKey(msgGet!!.final_from_wxid.toString())) {
                val time = redisDBB.opsForValue().operations.getExpire(msgGet!!.final_from_wxid.toString())

                MsgSend.sendText(msgGet!!.from_wxid, "请休息一会哦，剩余等待时间${time}秒")
                return
            }

            redisDBB.opsForValue().set(msgGet!!.final_from_wxid.toString(), msgGet!!.msg)
            redisDBB.expire(msgGet!!.final_from_wxid.toString(), astrict.time, astrict.timeUnit)

        }

        point.proceed(point.args)

    }


}